const service = require('../../services/clock-in-template-service');
const messages = require('../../common/messages');
const UiHelper = require('../../common/ui-helper');

const uiHelper = new UiHelper();

Page({
  data: {
    drawer: {
      visible: false,
      placement: 'right',
      sidebar: [],
      itemClick: null,
    },
    template: {
      id: null,
      name: '',
      iconName: '',
      content: '', // 富文本内容
    },
    options: {
      type: [
        { title: '', icon: 'accessibility' },
        { title: '', icon: 'battery-charging' },
        { title: '', icon: 'anchor' },
        { title: '', icon: 'address-book' },
        { title: '', icon: 'activity' },
        { title: '', icon: 'alarm-add' },
        { title: '', icon: 'alarm' },
        { title: '', icon: 'animation-1' },
        { title: '', icon: 'apple' },
        { title: '', icon: 'application' },
        { title: '', icon: 'assignment' },
        { title: '', icon: 'book' },
        { title: '', icon: 'key' },
        { title: '', icon: 'tag' },
      ],
    },
  },
  onLoad(options) {
    if (options && options.id !== null && options.id > 0) {
      this.initPageById(options.id);
    } else {
      this.resetPage();
    }
  },
  onReady() {},
  resetPage() {
    this.setData({
      template: {
        id: null,
        name: '',
        iconName: '',
        content: '', // 富文本内容
      },
    });
  },
  initPageById(id) {
    service
      .queryById(id)
      .then((res) => {
        const template = res.data;
        this.setData({ template });
        const content = template.content === null ? '' : template.content;
        uiHelper.writeContent('content-editor', content).catch(messages.showError);
      })
      .catch(messages.showError);
  },
  onShow() {},
  onNameInput(e) {
    this.setData({
      'template.name': e.detail.value,
    });
  },
  selectIcon: function () {
    this.openDrawerIcon(this.data.options.type, (e) => {
      this.setData({
        'template.iconName': e.detail.item.icon,
      });
    });
  },
  openDrawerIcon: function (range, receiver) {
    this.setData({
      drawer: {
        visible: true,
        sidebar: range,
        itemClick: receiver,
      },
    });
  },

  drawerItemClick: function (e) {
    this.data.drawer.itemClick(e);
    this.setData({
      'drawer.visible': false,
    });
  },

  onCancel: function () {
    wx.navigateBack();
  },

  onConfirm: function () {
    uiHelper
      .readContent('content-editor')
      .then((content) => {
        const { template } = this.data;
        template.content = content;
        if (template.id !== null && template.id > 0) {
          return service.update(template);
        }
        return service.create(template);
      })
      .then((res) => {
        if (res.statusCode !== 200) {
          throw res.data.error;
        }
        messages.showMessage('保存成功');
        wx.navigateBack();
      })
      .catch(messages.showError);
  },
});
